package org.yi.web.post;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yi.core.annotation.Action;
import org.yi.core.common.Constants;
import org.yi.core.enums.BlockTargetEnum;
import org.yi.core.enums.PostTypeEnum;
import org.yi.core.utils.ParamUtils;
import org.yi.web.account.entity.AccountEntity;
import org.yi.web.base.BaseController;
import org.yi.web.category.entity.CategoryEntity;
import org.yi.web.post.entity.PostEntity;
import org.yi.web.sys.entity.SiteEntity;

import com.jfinal.plugin.activerecord.Page;

@Action(action = "article")
public class ArticleController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
	
	public void index() {
		list();
	}
	
	public void list() {
		SiteEntity site = null;
		try {
			site = getSite();
			setAttr("site", site);
			setAttr("categoryList", CategoryEntity.dao.getAll());
			setAttr("categoryMap", CategoryEntity.dao.getIdTitleMap());
			setAttr("authorMap", AccountEntity.dao.getIdTitleMap());
			
			Map<String,String> params = ParamUtils.translateMap(getParaMap());
			params.put("category", getPara("cid"));
			params.put("type", PostTypeEnum.ARTICLE.getCode());
			Page<PostEntity> page = PostEntity.dao.getPager(getPager(), params);
			setAttr("page", page);
			
			loadBlocks(BlockTargetEnum.LIST);
			
			keepPara();
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		render("/themes/" + site.get("theme") + "/list.html");
	}
	
	public void show() {
		String id = getPara("id");
		SiteEntity site = null;
		try {
			site = getSite();
			setAttr("site", site);
			PostEntity p = PostEntity.dao.findById(id);
			setAttr("post", p);
			setAttr("categoryMap", CategoryEntity.dao.getIdTitleMap());
			setAttr("categoryList", CategoryEntity.dao.getAll());
			setAttr("authorMap", AccountEntity.dao.getIdTitleMap());
			// get last and next article
			PostEntity last = PostEntity.dao.getLast(p);
			PostEntity next = PostEntity.dao.getNext(p);
			setAttr("last", last);
			setAttr("next", next);
			
			List<PostEntity> nextList = PostEntity.dao.getNext(p, Constants.DEFAULT_PAGESIZE);
			// if nextList.size not enough, get PostEntity from the start
			if(nextList.size() < Constants.DEFAULT_PAGESIZE) {
				nextList.addAll(PostEntity.dao.getNext(null, Constants.DEFAULT_PAGESIZE-nextList.size()));
			}
			setAttr("nextList", nextList);
			
			loadBlocks(BlockTargetEnum.ARTICLE);
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		render("/themes/"+site.get("theme")+"/show.html");
	}

}
